package com.kk.my_pro.controller.system;


import com.kk.my_pro.common.result.ApiResult;

import com.kk.my_pro.common.utility.jwt.JwtUtil;
import com.kk.my_pro.common.utility.thread.RequestInfo;
import com.kk.my_pro.config.security.DBUserDetailsManager;
import com.kk.my_pro.entity.User;
import com.kk.my_pro.entity.form.LoginReuqestFrom;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/systemUser")
@Slf4j
public class SystemUserController {

    @Resource
    DBUserDetailsManager userService;
    @Resource
    PasswordEncoder passwordEncoder;


    @Resource
    AuthenticationManager authenticationManager;

    @Resource
    JwtUtil jwtUtil;

    @PostMapping("/login")
    public ApiResult<String> doLogin(@RequestBody LoginReuqestFrom request) {
        try {
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(request.getUserName(), request.getPassword());
            Authentication authentication = authenticationManager.authenticate(auth);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String jwtToken = jwtUtil.getToken(userDetails.getUsername());
            return ApiResult.success(jwtToken);
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("userName or password is not correct");
            return ApiResult.failure("登录失败");
        }
    }


    @PostMapping("/check")
    public ApiResult<String> doCheck(){
        log.info("权限验证成功");
        RequestInfo requestInfo = RequestInfo.get();
        return ApiResult.success(requestInfo+"校验成功");
    }

    @PostMapping("/register")
    public ApiResult<String> doRegister(@RequestBody User user) {
        try {
            if (user.getPassword() != null && !user.getPassword().isEmpty()) {
                String password = passwordEncoder.encode(user.getPassword());
                user.setPassword(password);
                user.setUserId(UUID.randomUUID().toString());
                if (userService.insertUser(user) == null) {
                    throw new Exception("用户名已存在");
                }
                String jwtToken = jwtUtil.getToken(user.getUserName());
                return ApiResult.success(jwtToken);
            } else
                throw new Exception("密码为空");
        } catch (Exception e) {
            log.error(e.getMessage());
            return ApiResult.failure("注册失败" + e.getMessage());
        }

    }
}
